package com.chaodev.base.utils;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.chaodev.base.base.RedisDao;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.Clob;
import java.sql.SQLException;
import java.util.*;

public class RequestParamerMap {
	@Autowired
	private static RedisDao redisDao;

	//常规参数转换
	public static Map<String, Object> getParamerMap(HttpServletRequest httpServletRequest) {
		Map<String,String[]> map=httpServletRequest.getParameterMap();
		Map<String,Object> valuesMap=new HashMap<String, Object>();
		Set<Map.Entry<String, String[]>> set=map.entrySet();
		boolean SPUrl = boolUrl(httpServletRequest);
		for(Map.Entry<String,String[]> entry:set)
		{
			try
			{
				String text=entry.getValue()[0];
				String key = entry.getKey();
				if(SPUrl || noFilter(key)){//如果是表单流程配置的方法，不过滤
					valuesMap.put(key, text);
				}else if(boolProType(key)){//如果是登录的用户名密码或者富文本内容
					text = StringUtils.stringFilterSP(text);
					valuesMap.put(key, text);
				}else{//其他类型参数
					text = StringUtils.stringFilter(text);
					valuesMap.put(key, text);
				}
			}
			catch(Exception e)
			{

			}
		}
		return valuesMap;
	}

	//分页参数转换
	public static Map<String, Object> getPostData(HttpServletRequest request) {
		StringBuffer data = new StringBuffer();
		String line = null;
		BufferedReader reader = null;
		try {
			reader = request.getReader();
			while (null != (line = reader.readLine()))
				data.append(line);
		} catch (IOException e) {

		} finally {

		}
		JSONObject jsonObject = JSONObject.parseObject(data.toString());
		Map<String, Object> dataMap = new HashMap<String, Object>();
		dataMap= JSONObject.parseObject(jsonObject.toJSONString(), new TypeReference<Map<String, Object>>(){});
		return dataMap;
	}

	public static JSONObject getJSONParam(HttpServletRequest request){
		JSONObject jsonParam = null;
		try {
			// 获取输入流
			BufferedReader streamReader = new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8"));

			// 写入数据到Stringbuilder
			StringBuilder sb = new StringBuilder();
			String line = null;
			while ((line = streamReader.readLine()) != null) {
				sb.append(line);
			}
			jsonParam = JSONObject.parseObject(sb.toString());
			// 直接将json信息打印出来
			System.out.println(jsonParam.toJSONString());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return jsonParam;
	}

	//数据分页
	public static Map<String, Object> getTableListMap(Map<String, Object> requestMap) {
		@SuppressWarnings("unchecked")
		List<Map<String, Object>> arr = ((ArrayList<Map<String, Object>>) requestMap.get("v_cursor1"));
		@SuppressWarnings("unchecked")
		Map<String, Object> map2 = ((ArrayList<Map<String, Object>>) requestMap.get("v_cursor2")).get(0);
		String total="";
		String currPage="";
		String totalPages="";
		//总记录条数
		if(map2!=null&&map2.get(":B3")!=null)
		{
			total = map2.get(":B3").toString();
		}
		//当前页
		if(map2!=null&&map2.get(":B4")!=null)
		{
			currPage = map2.get(":B4").toString();
		}
		//总页数
		if(map2!=null&&map2.get(":B2")!=null)
		{
			totalPages = map2.get(":B2").toString();
		}

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("Total",total);
		map.put("currPage",currPage);
		map.put("totalPages",totalPages);
		map.put("code","0");
		map.put("meg","数据加载成功");

		List<Map<String, Object>> list1 = new ArrayList<Map<String, Object>>();
		for (Map<String, Object> resultMap : arr) {
			Map<String, Object> map1 = new HashMap<String, Object>();
			for (String key : resultMap.keySet()) {
				if (resultMap.get(key).getClass().getName() == "oracle.sql.CLOB") {
					try {
						String competitive = StringUtils.ClobToString((Clob) resultMap.get(key));
						map1.put(key, competitive);
					} catch (SQLException e) {
						e.printStackTrace();
					} catch (IOException e) {
						e.printStackTrace();
					}
				} else {
					if (resultMap.containsKey(key)) {
						map1.put(key, resultMap.get(key).toString());
					}
				}
			}
			list1.add(map1);
		}
		map.put("Rows", list1);
		return map;
	}

	//数据中CLOB转换
	public static List<Map<String, Object>> getDataMap(Map<String, Object> requestMap) {
		@SuppressWarnings("unchecked")
		List<Map<String, Object>> arr = ((ArrayList<Map<String, Object>>) requestMap.get("v_cursor1"));

		List<Map<String, Object>> list1 = new ArrayList<Map<String, Object>>();
		for (Map<String, Object> resultMap : arr) {
			Map<String, Object> map1 = new HashMap<String, Object>();
			for (String key : resultMap.keySet()) {
				if (resultMap.get(key).getClass().getName() == "oracle.sql.CLOB") {
					try {
						String competitive = StringUtils.ClobToString((Clob) resultMap.get(key));
						map1.put(key, competitive);
					} catch (SQLException e) {
						e.printStackTrace();
					} catch (IOException e) {
						e.printStackTrace();
					}
				} else {
					if (resultMap.containsKey(key)) {
						map1.put(key, resultMap.get(key).toString());
					}
				}
			}
			list1.add(map1);
		}
		return list1;
	}

	//数据中CLOB转换
	public static List<Map<String, Object>> getDataMapNew(Map<String, Object> requestMap,String ipHost) {
		@SuppressWarnings("unchecked")
		List<Map<String, Object>> arr = ((ArrayList<Map<String, Object>>) requestMap.get("v_cursor1"));

		List<Map<String, Object>> list1 = new ArrayList<Map<String, Object>>();
		for (Map<String, Object> resultMap : arr) {
			Map<String, Object> map1 = new HashMap<String, Object>();
			for (String key : resultMap.keySet()) {
				if (resultMap.get(key).getClass().getName() == "oracle.sql.CLOB") {
					try {
						String competitive = StringUtils.ClobToString((Clob) resultMap.get(key));
						if(ipHost.indexOf("czmhbase")>-1)
						{
							competitive=competitive.replaceAll("172.17.5.204","10.124.48.22");
						}
						map1.put(key, competitive);
					} catch (SQLException e) {
						e.printStackTrace();
					} catch (IOException e) {
						e.printStackTrace();
					}
				} else {
					if (resultMap.containsKey(key)) {
						String nowvalue=resultMap.get(key).toString();
						if(ipHost.indexOf("czmhbase")>-1)
						{
							nowvalue=nowvalue.replaceAll("172.17.5.204","10.124.48.22");
						}
						map1.put(key, nowvalue);
					}
				}
			}
			map1.put("ipHost",ipHost);
			list1.add(map1);
		}
		return list1;
	}

	public static Map<String, Object> getZuiTableListMap(Map<String, Object> requestMap) {
		@SuppressWarnings("unchecked")
		List<Map<String, Object>> arr = ((ArrayList<Map<String, Object>>) requestMap.get("v_cursor"));

		@SuppressWarnings("unchecked")
		Map<String, Object> map2 = ((ArrayList<Map<String, Object>>) requestMap.get("v_cursor2")).get(0);
		Integer total=0;
		Integer page=0;
		Integer recPerPage=0;
		if(map2!=null&&map2.get(":B3")!=null)
		{
			total = Integer.parseInt(map2.get(":B3").toString()) ;
		}
		if(map2!=null&&map2.get(":B4")!=null)
		{
			page = Integer.parseInt(map2.get(":B4").toString()) ;
		}
		if(map2!=null&&map2.get(":B1")!=null)
		{
			recPerPage = Integer.parseInt(map2.get(":B1").toString());
		}

		Map<String, Object> pagermap = new HashMap<String, Object>();
		pagermap.put("recTotal", total);
		pagermap.put("page", page);
		pagermap.put("recPerPage", recPerPage);
		Map<String,Object> map=new HashMap<>();
		if(arr.size()>0){
			map.put("result","success");
			map.put("message","获取数据成功");
		}
		else if(arr.size()==0){
			map.put("result","error");
			map.put("message","暂无查询数据");
		}
		else{
			map.put("result","error");
			map.put("message","数据获取失败");
		}
		map.put("pager",pagermap);
		map.put("data", arr);
		return map;
	}

	public static String GetCookieID(HttpServletRequest request) {
		String cookieValue="";
		try
		{
			Cookie[] cookies = request.getCookies();
			Cookie cookie=cookies[0];
			//String cookieName= cookie.getName();
			cookieValue= cookie.getValue();
		}
		catch (Exception e) {
			// TODO: handle exception
		}

		return cookieValue;

	}

	//判断是否是富文本域传递的数据
	public static boolean boolProType(String arr){
		String[] typeArr = new String[]{"P_AppointmentContent","P_CONTENT","WORKPLAN_CONTENT","editorValue"};
		ArrayList<String> typeList = new ArrayList<String>(Arrays.asList(typeArr));
		boolean rt=false;
		if(typeList.contains(arr)){
			rt=true;
		}
		return rt;

	}

	//登录时的用户名和密码，以及上传附件的参数
	public static boolean noFilter(String arr){
		String[] typeArr = new String[]{"P_USERNAME","P_PASSWORD","file_path","P_PATH","file_url","FUJIAN_URL","P_FJ_RESULT","P_SINGNATUREURL",
				"P_RPANNEX","P_TRAININGANNEX","P_ANANNEX","V_MENU_PATH","P_Fujian","P_FUJIAN_URL","FJ_URL","V_LOOP_IMG","V_DEF_IMG","V_FILE_PATH",
				"V_LINK_URL","V_NTI_CONTENT","V_SURPORT_CONTENT","lineData","process_info"};
		ArrayList<String> typeList = new ArrayList<String>(Arrays.asList(typeArr));
		boolean rt=false;
		if(typeList.contains(arr)){
			rt=true;
		}
		return rt;
	}

	//判断URL，如果是表单配置的功能，不做处理
	public static boolean boolUrl(HttpServletRequest httpServletRequest){
		HttpServletRequest request = (HttpServletRequest)httpServletRequest;
		String[] urlArr = new String []{"FormContenAdd"};
		ArrayList<String> urlList = new ArrayList<>(Arrays.asList(urlArr));
		boolean rt = false;
		System.out.println(request.getRequestURI());
		String RequestUrl = request.getRequestURI();
		for (String url:urlList) {
			if (RequestUrl.indexOf(url)>0){
				return true;
			}
		}
		return rt;
	}
}
